<?php
declare(strict_types=1);
namespace Cache\Driver;
use Cache\CacheInterface;

class Apcu implements CacheInterface
{
    /**
     * 初始化
     * @return void
     */
    public function __contract(): void
    {
        if (!extension_loaded("apcu")) exit("apcu扩展未安装！");
    }

    /**
     * @inheritDoc
     */
    public function get(array|string $name): mixed
    {
        // TODO: Implement get() method.
        return apcu_fetch( $name );
    }

    /**
     * 自加
     * @param string $name
     * @param int $step
     * @return bool|int
     */
    public function inc(string $name, int $step = 1): bool|int
    {
        $value = $this->get($name) + $step;
        return $this->set($name,$value);
    }

    /**
     * 自减
     * @param string $name
     * @param int $step
     * @return bool|int
     */
    public function dec(string $name, int $step = 1): bool|int
    {
        $value = $this->get($name) - $step;
        return $this->set($name,$value);
    }

    /**
     * @inheritDoc
     */
    public function set(string $name, mixed $value, ?int $expire = null): bool
    {
        // TODO: Implement set() method.
        return apcu_store( $name, $value, $expire?:0 );
    }

    /**
     * @inheritDoc
     */
    public function delete(array|string $name): bool
    {
        // TODO: Implement delete() method.
        return apcu_delete($name);
    }

    /**
     * @inheritDoc
     */
    public function flush(): bool
    {
        // TODO: Implement flush() method.
        return apcu_clear_cache();
    }
}
